package com.github.shiqiyue.app.common.filter;


import com.github.shiqiyue.app.common.result.Result;
import com.github.shiqiyue.app.common.result.ResultMsg;
import com.github.shiqiyue.app.common.utils.IpUtils;
import com.github.shiqiyue.app.common.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/***
 * 安全过滤器-验证User-Agent和Ip是否和session中的一致
 * @author wenyao.wu
 */
@Slf4j
public class UserAgentAndIpFilter extends PathConfigurableFilter {


    /***
     *  useragent存放到session中的key
     */
    private String sessionKeyUserAgent;

    /***
     * ip存放到session的key
     */
    private String sessionKeyIp;


    @Override
    protected void doFiltering(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        try {
            // 用户登录后，会在session中保存user-agent和ip；
            // 这里需要比较请求的user-agent和ip是否与session中的一致；
            String userAgent = httpServletRequest.getHeader(HttpHeaders.USER_AGENT);
            String ip = IpUtils.getIpAddr(httpServletRequest);
            HttpSession httpSession = httpServletRequest.getSession();
            String sessionUserAgent = (String) httpSession.getAttribute(sessionKeyUserAgent);
            String sessionIp = (String) httpSession.getAttribute(sessionKeyIp);
            boolean isSame = StringUtils.isNotBlank(sessionIp) && sessionIp.equals(ip)
                    && StringUtils.isNotBlank(sessionUserAgent) && sessionUserAgent.equals(userAgent);
            if (isSame) {
                filterChain.doFilter(httpServletRequest, httpServletResponse);
                return;
            } else {
                log.warn("User agent或者ip与缓存不一致");
                ResponseUtils.populateResponse(ResponseEntity.ok(Result.fail(ResultMsg.REQUEST_ERROR)), httpServletResponse);
                return;
            }
        } catch (Exception e) {
            log.error("UserAgentAndIpFilter异常", e);
            ResponseUtils.populateResponse(ResponseEntity.ok(Result.fail(ResultMsg.REQUEST_ERROR)), httpServletResponse);
            return;
        }
    }


    public void setSessionKeyUserAgent(String sessionKeyUserAgent) {
        this.sessionKeyUserAgent = sessionKeyUserAgent;
    }

    public void setSessionKeyIp(String sessionKeyIp) {
        this.sessionKeyIp = sessionKeyIp;
    }
}
